package com.example.idlefish.MyAccount.activity

import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.widget.Toast
import androidx.appcompat.app.*
import java.io.*

class PhotoActivity : AppCompatActivity() {

    private var mFilePath: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // setContentView(R.layout.activity_main)

        if (getExternalStoragePath(this) != "") {
            mFilePath = getExternalStoragePath(this)
        } else {
            Toast.makeText(this, "无法获取外部存储路径", Toast.LENGTH_SHORT).show()
            return
        }

        mFilePath += "/${System.currentTimeMillis()}.png"

        // 确保路径是绝对路径
        val absolutePath = File(mFilePath).absolutePath

        // 插入媒体库
        insertImageIntoMediaStore(this, absolutePath)
    }

    private fun getExternalStoragePath(context: Context): String {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val appSpecificDir = context.getExternalFilesDir(null)
            appSpecificDir?.path ?: ""
        } else {
            Environment.getExternalStorageDirectory().path
        }
    }

    private fun insertImageIntoMediaStore(context: Context, absolutePath: String) {
        val values = ContentValues().apply {
            put(MediaStore.Images.Media.MIME_TYPE, "image/png")
            put(MediaStore.Images.Media.DISPLAY_NAME, File(absolutePath).name)
            put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Camera")
            put(MediaStore.Images.Media.IS_PENDING, 1)
        }

        val myCameraUri: Uri? = context.contentResolver.insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            values
        )

        if (myCameraUri == null) {
            Toast.makeText(context, "无法插入图片到媒体库", Toast.LENGTH_SHORT).show()
            return
        }

        // 写入文件内容
        context.contentResolver.openOutputStream(myCameraUri)?.use { outputStream ->
            File(absolutePath).inputStream().use { inputStream ->
                inputStream.copyTo(outputStream)
            }
        }

        // 更新 IS_PENDING 为 0
        values.clear()
        values.put(MediaStore.Images.Media.IS_PENDING, 0)
        context.contentResolver.update(myCameraUri, values, null, null)

        Toast.makeText(context, "图片已成功插入媒体库", Toast.LENGTH_SHORT).show()
    }
}